package com.jie.langlangmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.jie.langlangmall.common.constant.StatusConstant;
import com.jie.langlangmall.dto.UmsMenuNode;
import com.jie.langlangmall.mapper.UmsMenuMapper;
import com.jie.langlangmall.model.UmsMenu;
import com.jie.langlangmall.model.UmsMenuExample;
import com.jie.langlangmall.service.UmsMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Jie
 * @Date 2024/11/22 15:45
 * @Email 3217998214@qq.com
 * @Description 后台菜单管理
 */
@Service
@Slf4j
public class UmsMenuServiceImpl implements UmsMenuService {

    @Autowired
    private UmsMenuMapper menuMapper;

    /**
     * 树形结构返回所有菜单列表
     *
     * @return
     */
    @Override
    public List<UmsMenuNode> treeList() {
        // 1. 先查询所有的菜单
        List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
        // 2. 组装成树形结构
        return menuList.stream()
                .filter(menu -> menu.getParentId().equals(0L)) // 先找到所有的一级菜单
                .map(menu -> covertMenuNode(menu, menuList)) // 一级菜单及一下的所有子菜单进行递归设置
                .collect(Collectors.toList());
    }

    /**
     * 分页查询菜单
     *
     * @param parentId
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UmsMenuExample example = new UmsMenuExample();
        example.setOrderByClause("sort desc");
        example.createCriteria().andParentIdEqualTo(parentId);
        // select * from ums_menu where parent_id = parentId
        return menuMapper.selectByExample(example);
    }

    /**
     * 修改菜单显示状态
     *
     * @param id
     * @param hidden
     * @return
     */
    @Override
    public int updateHidden(Long id, Integer hidden) {
        UmsMenu umsMenu = new UmsMenu();
        umsMenu.setId(id);
        umsMenu.setHidden(hidden);
        // 更新数据库
        menuMapper.updateByPrimaryKeySelective(umsMenu);
        return StatusConstant.SUCCESS;
    }

    @Override
    public UmsMenu getItem(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改后台菜单
     *
     * @param id
     * @param umsMenu
     * @return
     */
    @Override
    public int update(Long id, UmsMenu umsMenu) {
        umsMenu.setId(id);
        // TODO: 更新菜单的级别
        updateLevel(umsMenu);
        menuMapper.updateByPrimaryKeySelective(umsMenu);
        // TODO: 需要更新缓存吗？
        return StatusConstant.SUCCESS;
    }

    /**
     * 新增菜单
     *
     * @param umsMenu
     * @return
     */
    @Override
    public int create(UmsMenu umsMenu) {
        umsMenu.setCreateTime(new Date());
        // 设置菜单的级别
        updateLevel(umsMenu);
        menuMapper.insert(umsMenu);
        return StatusConstant.SUCCESS;
    }

    /**
     * 根据id删除菜单
     *
     * @param id
     * @return
     */
    @Override
    public int delete(Long id) {
        List<Long> childrenIds = getChildrenIds(id, menuMapper.selectByExample(new UmsMenuExample()));
        childrenIds.add(id);
        UmsMenuExample example = new UmsMenuExample();
        example.createCriteria().andIdIn(childrenIds);
        // 数据库删除
        menuMapper.deleteByExample(example);
        // TODO: 关联表怎么办？
//        menuMapper.deleteByPrimaryKey(id);
        // TODO: 需要更新缓存？
        return StatusConstant.SUCCESS;
    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性
     *
     * @param menu
     * @param menuList
     * @return
     */
    private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
        UmsMenuNode node = new UmsMenuNode();
        BeanUtils.copyProperties(menu, node);
        List<UmsMenuNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId())) // 子菜单，父节点的id等于menu的id
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList()); // 子菜单继续递归
        node.setChildren(children);
        return node;
    }

    /**
     * 修改菜单的层级
     *
     * @param umsMenu
     */
    private void updateLevel(UmsMenu umsMenu) {
        if (umsMenu.getParentId() == 0) {
            //没有父菜单时为一级菜单
            umsMenu.setLevel(0);
        } else {
            //有父菜单时选择根据父菜单level设置
            UmsMenu parentMenu = menuMapper.selectByPrimaryKey(umsMenu.getParentId());
            if (parentMenu != null) {
                umsMenu.setLevel(parentMenu.getLevel() + 1);
            } else {
                umsMenu.setLevel(0);
            }
        }
    }

    /**
     * 获取parentId下的所有子菜单
     *
     * @param parentId
     * @return
     */
    private List<Long> getChildrenIds(Long parentId, List<UmsMenu> menuList) {
        List<Long> result = menuList.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .map(UmsMenu::getId)
                .collect(Collectors.toList());
        for (Long id : result) {
            result.addAll(getChildrenIds(id, menuList));
        }
        return result;
    }
}
